﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TA.JSON
{
	/// <summary>
	/// Deserializes JSON input.
	/// </summary>
	public interface IJsonDeserializable
	{
		/// <summary>
		/// When implemented, deserializes the JSON from the supplied JsonReader into the target object.
		/// </summary>
		/// <param name="jr">The JsonReader.</param>
		void Deserialize(IJsonReader jr);
		/// <summary>
		/// When implemented, deserializes the JSON from the supplied JsonReader into the property of the target object as specified by propShortName.
		/// </summary>
		/// <param name="propShortName">The short name of the property that needs to be deserialized, or null if an element in a list/enumeration.</param>
		/// <param name="jr">The JsonReader.</param>
		void DeserializeContent(IJsonReader jr, string propShortName);
	}
	/// <summary>
	/// Extensions for IJsonDeserializable interface.
	/// </summary>
	public static class _IJsonDeserializableExtensions
	{
		/// <summary>
		/// Performs common tasks necessary when deserializing an object.
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="jr"></param>
		public static void DeserializeObject(this IJsonDeserializable obj, IJsonReader jr)
		{
			jr.Read(JsonToken.StartObject);

			while (jr.TokenType == JsonToken.PropertyName)
			{
				string prShortName = (string)jr.Value;
				jr.Read();

				obj.DeserializeContent(jr, prShortName);
				jr.Read();
			}
			jr.Expect(JsonToken.EndObject);
		}
		/// <summary>
		/// Performs common tasks necessary when deserializing an array.
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="jr"></param>
		public static void DeserializeArray(this IJsonDeserializable obj, IJsonReader jr)
		{
			jr.Read(JsonToken.StartArray);

			while (jr.TokenType != JsonToken.EndArray)
			{
				obj.DeserializeContent(jr, null);
				jr.Read();
			}

			jr.Expect(JsonToken.EndArray);
		}

	}
}
